<template>
  <div>
    <div class="p20 send_box">
      <div class="comment-sheet">
        <!--      <div class="content">发布评论</div>-->
        <!--      <div class="send" @click="newaddComment">发送</div>-->
      </div>
      <!--        <div contenteditable="true" v-model="message" v-html="$options.filters.toimg(message)"></div>-->
      <van-field
        v-model="message"
        id="inputHeight"
        ref="show_input"
        rows="4"
        autosize
        type="textarea"
        clearable
        @focus="focus_input"
        placeholder="发一条友善的评论吧~"
      />
      <template v-for="(item, index) in fileList2">
        <div style="position: relative; display: inline-block; margin-right: 3px">
          <img class="send_img" :src="item" alt="" />
          <van-icon @click="delete_img(item, index)" name="cross" class="delete_img" />
        </div>
      </template>
      <!--        <div v-html="$options.filters.toimg(ceshi)"></div>-->
      <div class="mt10 flex">
        <div>
          <img class="mr20" src="@/assets/images/face_logo.svg" alt="" @click="show_emoji_f" />
          <!-- <van-uploader
          v-if="isAndroid"
            v-model="fileList"
            multiple
            :preview-image="false"
            :before-read="beforeRead"
            :after-read="afterRead"
            :max-count="6"
            accept="image/*"
          >
            <img src="@/assets/images/pic_logo.svg" alt=""/>
          </van-uploader> -->
          <img  @click="handleClick" src="@/assets/images/pic_logo.svg" alt=""/>
        </div>

        <div class="send" :class="[message ? 'yellow' : 'zi']" @click="newaddComment">发布</div>
      </div>
    </div>
    <div style="width: 100%; height: 1px; background: rgb(237 238 238)"></div>
    <template v-if="show_emoji">
      <div class="" style="background: #f0f0f078; padding: 20px 0 0 0; height: 170px; overflow: auto">
        <emoji @chooseEmoji="chooseEmoji"></emoji>
      </div>
    </template>
  </div>
</template>

<script>
import { newaddComment, NewaddReply } from '@/api/api_z'
import { weixinMojiTranslate } from '@/utils/emoji'
import { client } from '@/utils/alioss'
import emoji from './emoji'
export default {
  name: 'send-message',
  components: {
    emoji
  },
  props: {
    commentData: '',
    clear: true,
    level: '',
    fullScreenId: ''
  },
  watch: {
    clear: {
      handler(newvalue, oldvalue) {
        debugger
      }
    }
  },
  data() {
    return {
      hasData: false,
      fileList: [],
      fileList2: [],
      images: '',
      show_emoji: false,
      message: '',
      spaceInfo: JSON.parse(localStorage.getItem('spaceInfo')),
      androidAttrs: null,
      isAndroid:true,

      isoFilename:'name'

    }
  },
  created() {
    this.checkedIsIos()

  },
  mounted() {
    // window.onresize监听页面高度的变化
    window.onresize = () => {
      return (() => {
      // alert('1')
      console.log('11111')
        // window.scroll(0, 0) // 滚到顶部
        document.getElementById(this.fullScreenId).scrollTop = document.getElementById(this.fullScreenId).scrollHeight
      })()
    }
    let _this = this
    window.takePictureCallBack = function (res) {
      _this.takePictureCallBack(res)
    }

  },

  methods: {
    // base64转blob
  dataURLtoBlob(dataurl) { 
        var bstr = atob(dataurl),
              n = bstr.length,
              u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr]);
  },
    handleClick(){
      // let filesName = new Date().getTime().toString()+'name'
      // console.log('222',filesName)
      // console.log('ios',window.ccworkBridge)
      // window.ccworkBridge.ccworkGetPicsFromAlbumV2({
      //   maxNum:6,
      //   mType:0,
      //   piciterable(file,data){
      //     console.log('aa',file,data)
      //   },
      // }
      window.ccworkBridge.ccworkGetPicsFromAlbum({
        // quality:'mid',
        // mode:'both',
        // piciterable(fileDta){
        //   let fileName=fileDta
        // }
        maxNum:9,
        mType:0
      }
      ,(e)=>{
        console.log('result',e);

        e.result.forEach((item,index)=>{
          let filesName = new Date().getTime().toString()+'name'+index
          console.log('222',filesName)
          client().multipartUpload(filesName,this.dataURLtoBlob(item.content))
        .then(result => {
            console.log('上传成功',result)
            if (result.res.statusCode == 200) {
              // resolve(result.res);
              let fileUrl = result.res.requestUrls[0] ? result.res.requestUrls[0].split('?')[0] : ''
              // _this.submit_file.push(detail.name.v_model);
              var img_list = {
                url: fileUrl
              }
              this.fileList2.push(fileUrl)
              // resolve(result)
            } else {
              this.$toast('上传出错')
            }
          })
          .catch(err => {
            console.log('失败',err)
            // reject();
          })
        })

      })
    },
    focus_input(e) {
      const _this = this
    },
    delete_img(item, index) {
      this.fileList2.splice(index, 1)
      this.fileList.splice(index, 1)
    },
beforeRead(file){
  console.log('before',file)
  return true
},

    async afterRead(file, detail) {
      console.log('after',file,detail)
      // debugger;
      // 此时可以自行将文件上传至服务器
      const _this = this
      if (file.length > 0) {
        //多张图
        await Promise.all(
          file.map(val => {
            return new Promise((resolve, reject) => {
              let fileName = val.file.lastModified + val.file.name
              client()
                .multipartUpload(fileName, val.file)
                .then(result => {
                  if (result.res.statusCode == 200) {
                    // resolve(result.res);
                    let fileUrl = result.res.requestUrls[0] ? result.res.requestUrls[0].split('?')[0] : ''
                    // _this.submit_file.push(detail.name.v_model);
                    var img_list = {
                      url: fileUrl
                    }
                    _this.fileList2.push(fileUrl)
                    resolve(result)
                  } else {
                    _this.$toast('上传出错')
                  }
                })
                .catch(err => {
                  console.log(err)
                  // reject();
                })
            })
          })
        )
      } else {
        //单张图
        let fileName = file.file.lastModified + file.file.name
        client()
          .multipartUpload(fileName, file.file)
          .then(result => {
            if (result.res.statusCode == 200) {
              // resolve(result.res);
              let fileUrl = result.res.requestUrls[0] ? result.res.requestUrls[0].split('?')[0] : ''
              // _this.submit_file.push(detail.name.v_model);
              var img_list = {
                url: fileUrl
              }
              _this.fileList2.push(fileUrl)
              resolve(result)
            } else {
              _this.$toast('上传出错')
            }
          })
          .catch(err => {
            console.log(err)
          })
      }

      console.log(this.fileList2.toString())
    },
    //发布评论
    newaddComment() {
      const _this = this
      if (this.message == '') {
        this.$toast({
          message: '最少填写一个字才可发布',
          position: 'bottom'
        })
        return false
      }
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0
      })
      /*  if((this.message=='')&&(this.fileList2.toString()=='')){
        return false
      }*/
      let { targetType, targetId, menuId } = this.commentData
      let params = { targetType, targetId, content: this.message, images: this.fileList2.toString() }
      let params2 = {
        targetType,
        commentId: this.commentData.commentId,
        targetReplyId: this.commentData.targetId,
        replyType: '2',
        toUserId: this.commentData.createUserId,
        content: this.message,
        images: this.fileList2.toString()
      }
      if (this.level == 1) {
        newaddComment(params, _this.spaceInfo.id)
          .then(res => {
            _this.$toast('发表成功')
            _this.message = ''
            _this.fileList = []
            _this.fileList2 = []
            _this.$emit('changeData')
          })
          .catch(err => {
            console.log(error)
          })
      } else if (this.level == 2) {
        NewaddReply(params2, _this.spaceInfo.id)
          .then(res => {
            _this.$toast('发表成功')
            _this.message = ''
            _this.fileList = []
            _this.fileList2 = []
            _this.$emit('changeData')
          })
          .catch()
      }
    },
    //选择表情
    chooseEmoji(val) {
      const _this = this
      this.message += val
      // debugger
    },

    handlerComment() {
      this.show = true
      this.message = ''
    },
    show_emoji_f() {
      this.show_emoji = !this.show_emoji
      // this.show_emoji==false? this.show_emoji=true:this.show_emoji=false
    },

    // 判断ios
    checkedIsIos() {
      //获取浏览器的userAgent,并转化为小写
      var ua = navigator.userAgent
      //判断是否是苹果手机，是则是true
      // var isIoss = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);

      var isIos = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
      this.isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1 //android终端
      this.androidAttrs = ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1

      console.log('androidAttrs', this.androidAttrs, 'isAndroid')
    },

    solveCoverWays() {
    // 获取input元素底部bottom及整体高度
    let inputHeight = document.getElementById(this.fullScreenId);
    let inputInfo = window.getComputedStyle(inputHeight, null);
    let inputInfoH = parseInt(inputInfo.height.replace('px',''))

    // 获取文档当前聚焦的元素
    const { activeElement } = document;
    if (!['INPUT', 'TEXTAREA'].includes(activeElement.tagName.toUpperCase())) return;
    const rect = activeElement.getBoundingClientRect();
    if (!rect) return;

    // 设置初始滑动高度 ，聚焦元素到顶部的距离减去可视区的高度，如果大于0，就说明被遮挡住了，此时需要滚动到可视区内
    let scrollHeight = 0
    scrollHeight = rect.bottom  - (document.documentElement.clientHeight || document.body.clientHeight);

    // 判断当前focus的input底部是否在document.body可视区域内
      if (scrollHeight > 0) {
        document.body.scrollTop = scrollHeight + inputInfoH;
        document.documentElement.scrollTop = scrollHeight + inputInfoH;
        this.scrollTopHeightVal = scrollHeight + inputInfoH;
      }
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .van-popup--bottom.van-popup--round {
  padding: 16px;

  .content {
    font-size: 16px;
    font-family: Helvetica;
    color: #333333;
    line-height: 20px;
  }

  .send {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #fff;
    line-height: 20px;
  }
}
.comment-sheet {
  display: flex;
  justify-content: space-between;
}
::v-deep .van-cell {
  padding: 12px 0;
}
/deep/.van-list__finished-text {
  margin-bottom: 20px;
}
/deep/.send_comment.van-popup--bottom.van-popup--round {
  padding: 0;
}
.comment .van-cell::after {
  border-bottom: none;
}
.send_img {
  object-fit: cover;
  width: 50px;
  height: 50px;
}
.delete_img {
  right: 0;
  background: #000;
  color: #fff;
  position: absolute;
}
/deep/.van-field__body {
  background: rgb(246, 248, 250);
  border-radius: 6px;
}
/deep/.van-field__control {
  background: rgb(246, 248, 250);
  border-radius: 6px;
}

/deep/textarea::-webkit-input-placeholder {
  color: #a5a5b7;
}
/deep/.send_box .van-cell {
  padding: 0 0 15px 0;
}
</style>
